
def convert(imgf, labelf, outf, n):
    f = open(imgf, "rb")
    o = open(outf, "w")
    l = open(labelf, "rb")

    # 16个字节以后的，是图片的灰度值
    f.read(16)
    # 8个字节以后的，是取值为对应0-9之间的标签数字
    l.read(8)
    images = []

    for i in range(n):
        # ord返回对应的十进制数,返回对应的 ASCII 数值

        image = [ord(l.read(1))]
        for j in range(28*28):
            image.append(ord(f.read(1)))
        images.append(image)

    for image in images:
        o.write(",".join(str(pix) for pix in image)+"\n")

    f.close()
    o.close()
    l.close()


convert("./resources/train-images-idx3-ubyte/train-images.idx3-ubyte",
        "./resources/train-labels-idx1-ubyte/train-labels.idx1-ubyte",
        "./resources/MNISTcsv/mnist_train_500.csv", 500)
convert("./resources/t10k-images-idx3-ubyte/t10k-images.idx3-ubyte",
        "./resources/t10k-labels-idx1-ubyte/t10k-labels.idx1-ubyte",
        "./resources/MNISTcsv/mnist_test_200.csv", 200)
